package com.af.financeomine.web.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.vraptor.annotations.Component;
import org.vraptor.annotations.Remotable;
import org.vraptor.annotations.Viewless;

import com.af.financeomine.dao.PeriodoDao;
import com.af.financeomine.model.Periodo;
import com.af.financeomine.web.flexigrid.FlexigridRows;

@Component
public class PeriodoLogic {

	private static Logger log = Logger.getLogger(PeriodoLogic.class.getName());
	private PeriodoDao dao;
	private List<FlexigridRows> rows;
	private int total;
	private int page = 1;

	public PeriodoLogic(PeriodoDao dao ) {
		this.dao = dao;
	}
	
	@Viewless
	public void create(){
		
		Date dataAtual = new Date();
		Calendar c = Calendar.getInstance();
		
		List<Periodo> list = dao.findAfterDate(dataAtual);
		int size = list.size();
		if(size <3){		
			try{
				for(int i = 3; i > size; i--){
					c.setTime(dataAtual);
					c.add(Calendar.MONTH, i);
					c.set(Calendar.DAY_OF_MONTH, 1);
					Periodo p = new Periodo();
					p.setDataInicio(new Date(c.getTimeInMillis()));
					c.add(Calendar.MONTH, 1);
					c.add(Calendar.DAY_OF_MONTH, -1);
					p.setDataFim(new Date(c.getTimeInMillis()));
					p.setDescricao(c.getDisplayName(Calendar.MONTH, Calendar.LONG, new Locale("pt","BR")));
					dao.save(p);
				}
				
			}catch (Throwable e) {
				log.log(Level.SEVERE, "erro inesperado: "+ e.getMessage());
			}
		}
	}

	@Remotable
	public void lista(Integer page,String qtype, Integer rp,String sortname,String sortorder, String query){
		List<Periodo> periodos = dao.lista(page, qtype, rp, sortname, sortorder, query);
		total = periodos.size();
		rows = new ArrayList<FlexigridRows>(total);
		for (int i = 0; i < total;i++) {
			rows.add(new FlexigridRows(periodos.get(i)));
		}
	}
	
	public List<FlexigridRows> getRows() {
		return rows;
	}
	
	public int getTotal() {
		return total;
	}
	
	public int getPage() {
		return page;
	}
}
